package com.fractalist.man.task;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.log4j.Logger;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.util.FileCopyUtils;

import com.fractalist.man.base.SqlUtils;
import com.fractalist.man.service.IUserFieldService;
import com.fractalist.man.service.IUserService;

/**
 * 定时任务调用
 * 
 * @author samoin
 * @since 2013.2.27
 * 
 */
public class UserTask extends ApplicationObjectSupport {
	public static final Logger LOG = Logger.getLogger(UserTask.class);

	/**
	 * 从url里读取数据, 当出现在异常时返回空字符串
	 * 
	 * @param url
	 *            url字符串
	 * @param encoding
	 *            url的资源编码方式, 如果不提供则为utf-8
	 * @return 返回取得的字符串
	 * @throws IOException
	 */
	public static String url2String(String url, String... encode) {
		StringWriter sw = new StringWriter();
		try {
			url2Writer(url, sw, encode);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return "";
		}
		return sw.toString();
	}

	public static void url2Writer(String url, Writer writer, String... encode) {
		int maxTime = 1; // 重试次数
		int retry = 0;
		boolean httpSuss = false;
		while ((!httpSuss) && retry < maxTime) {
			retry++;
			httpSuss = _url2Writer(url, writer, encode.length == 0 ? "utf-8"
					: encode[0]);
			if (!httpSuss) {
				System.out.println("第" + retry + "次GET失败：" + url);
			}
		}
	}

	/**
	 * 加入对http response code的判断的url资源读取
	 * 
	 * @param url
	 * @param writer
	 * @param encode
	 * @return
	 */
	private static boolean _url2Writer(String url, Writer writer, String encode) {
		try {
			HttpURLConnection httpConnection = (HttpURLConnection) new URL(url)
					.openConnection();
			httpConnection.setRequestMethod("GET");
			httpConnection.setInstanceFollowRedirects(false);
			httpConnection.setRequestProperty("User-Agent",
					"Mozilla/5.0 Gecko/20110614 Firefox/3.6.18");
			// httpConnection.setRequestProperty("Accept-Encoding",
			// "gzip,deflate");
			httpConnection.setConnectTimeout(3 * 1000);
			httpConnection.setReadTimeout(10 * 1000);
			httpConnection.connect();
			int code = httpConnection.getResponseCode();
			if (code == HttpURLConnection.HTTP_OK) {
				Reader in = new BufferedReader(new InputStreamReader(
						httpConnection.getInputStream(), encode));
				FileCopyUtils.copy(in, writer);
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

		return false;
	}

	public void updateUserAge() {
		IUserFieldService userFieldService = (IUserFieldService) getApplicationContext()
				.getBean("userFieldService");
		userFieldService.update("update man_base_user_field set age = age + 1");
		SqlUtils.print("触发定时任务，给每个用户的年龄加1");
	}
}
